package com.atxwq.shop.manager.serivce.impl;

import com.atxwq.shop.common.log.annotation.Log;
import com.atxwq.shop.common.log.enums.OperatorType;
import com.atxwq.shop.manager.mapper.SysRoleMapper;
import com.atxwq.shop.manager.mapper.SysRoleUserMapper;
import com.atxwq.shop.manager.serivce.SysRoleService;
import com.atxwq.shop.model.dto.system.AssginRoleDto;
import com.atxwq.shop.model.dto.system.SysRoleDto;
import com.atxwq.shop.model.entity.system.SysRole;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 角色服务层
 * @Date 2025/5/9 13:05
 * @Created by 12336
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    /**
     * 分页查询角色列表
     * @param current
     * @param limit
     * @param sysRoleDto
     * @return
     */
    //@Log(title = "角色管理：列表展示", businessType = 0, operatorType = OperatorType.OTHER)
    @Override
    public PageInfo<SysRole> findByPage(Integer current, Integer limit, SysRoleDto sysRoleDto) {
        //设置分页参数
        PageHelper.startPage(current, limit);
        //查询
        List<SysRole> sysRoleList = sysRoleMapper.findByPage(sysRoleDto);
        //封装分页对象
        PageInfo<SysRole> pageInfo = new PageInfo<>(sysRoleList);
        return pageInfo;
    }

    /**
     * 添加角色
     * @param sysRole
     */
    //do 删除使用逻辑删除，添加角色的时候也要加入逻辑添加实现，否则会出现重复的user_code角色存入数据库
    @Override
    public void saveSysRole(SysRole sysRole) {
        //根据角色编码和角色名称查询角色，如果添加了重复角色则将isDeleted设置为0
        SysRole dbSysRole = sysRoleMapper.selectByRoleCodeAndRoleName(sysRole.getRoleCode(), sysRole.getRoleName());
        if (dbSysRole != null && dbSysRole.getIsDeleted() == 1) {
            dbSysRole.setIsDeleted(0);
            sysRoleMapper.updateSysRole(dbSysRole);
        }else {
            sysRoleMapper.saveSysRole(sysRole);
        }
    }

    /**
     * 修改角色
     * @param sysRole
     */
    @Override
    public void updateSysRole(SysRole sysRole) {
        sysRoleMapper.updateSysRole(sysRole);
    }

    /**
     * 删除角色
     * @param roleId
     */
    public void deleteById(Long roleId) {
        sysRoleMapper.deleteById(roleId);
    }

    /**
     * 查询所有角色
     * @return
     */
    @Override
    public Map<String, Object> findAllRoles(Long userId) {
        //1。查询所有角色
        List<SysRole> roleList = sysRoleMapper.findAllRoles();

        //2，查询分配过的角色
        //根据userId查询分配过的角色id
        List<Long> roleIds = sysRoleUserMapper.selecetRoleIdsByUserId(userId);

        Map<String, Object> map = new HashMap<>();
        map.put("allRolesList", roleList);
        map.put("sysUserRoles",roleIds);
        return map;
    }


}
